# routes/task_routes.py
from flask import Blueprint
from models.article import Article
import uuid
from flask import Flask, request, jsonify
from utils.logger import logger
import os
from utils.response import api_response

task_bp = Blueprint('/task', __name__)

from models.database import db
import json
# 正确的导入语句（根据实际文件名调整）
from crawler.JgCrawler import JgCrawler

@task_bp.route('/task/test')
def test():
    return  api_response(data={'orders': ['order1', 'order2', 'order3']})

@task_bp.route('/task/add', methods=['POST'])
def add_task():
    task_id = str(uuid.uuid4())
    logger.info(f"add_task:{task_id}")
    return api_response(data={'task_id': task_id})

@task_bp.route('/task/grapJg', methods=['GET'])
def grapJg():
    start_year = request.args.get('start_year',2003)
    end_year = request.args.get('end_year',2003)
    if start_year == "" or end_year == "":
        return api_response(code=1, message='参数错误')
    if int(start_year) > int(end_year):
        return api_response(code=1, message="参数错误")
    logger.info(f"grapJg:{start_year},{end_year}")
    crawler = JgCrawler()
    crawler.grap_jg_page(int(start_year),int(end_year))
    return api_response()
@task_bp.route('/task/grapJgFile', methods=['GET'])
def grapJgFile():
    start_year = request.args.get('start_year',2003)
    end_year = request.args.get('end_year',2003)
    if start_year == "" or end_year == "":
        return api_response(code=1, message="参数错误")
    if int(start_year) > int(end_year):
        return api_response(code=1, message="参数错误")
    logger.info(f"grapJgFile:{start_year},{end_year}")
    crawler = JgCrawler()
    crawler.grap_jg_file_page(int(start_year),int(end_year))
    return api_response()
@task_bp.route('/task/saveArticleToFile', methods=['GET'])
def save_article_to_file():
    actionType = request.args.get('type',1)
    logger.info(f"save_article_to_file:{actionType} {type(actionType)}")
    list = Article.query.filter_by(type=actionType).all()
    index = 0
    tempIndex = 0
    for article in list:
        title = article.title
        if actionType == "2":
            titleList = article.title.split("关于")
            logger.info(f"titleList:{titleList}")
            if len(titleList) >= 2:
                title = "关于" + titleList[1]
            title = title.replace(" ", "")
            title = title.replace("(有效)", "")
            title = title.replace("(已废止)", "")
        #title 超过45个字符
        if len(title) > 45:
            title = title[:21] + "***" + title[len(title)-21:]
        logger.info(f"save_article_to_file:{title}")
        current_dir = os.path.dirname(os.path.abspath(__file__))
        parent_dir = os.path.dirname(current_dir)
        if not os.path.exists(parent_dir + f"/temp/{actionType}/{tempIndex}"):
            os.makedirs(parent_dir + f"/temp/{actionType}/{tempIndex}")
        filePath = os.path.join(parent_dir, f"temp/{actionType}/{tempIndex}/{title}.txt")
        index += 1
        # 30个为一组
        if index % 30 == 0:
            tempIndex += 1
        
        #保存信息到文件
        with open(filePath, "w", encoding="utf-8") as f:
            content = article.content
            logger.info(f"content:{repr(content)}")
            if actionType == "2":
                # 去除content的前三行
                content = "\n".join(content.split("\n")[3:])
                logger.info(f"content000000:{content}")
            logger.info(f"content:{content}")
            f.write(content)
        # if tempIndex == 1:
        #     break
        # break
    return api_response()

    